package com.violet.detective.controller;

import com.violet.detective.entity.User;
import com.violet.detective.service.UserService;
import com.violet.detective.util.R;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/register")
    public R register(@RequestBody User user) {
        boolean result = userService.registerUser(user);
        return result ? R.ok() : R.error();
    }

    @PostMapping("/changePassword")
    public R changePassword(@RequestBody Map<String, String> payload) {
        String account = payload.get("account");
        String name = payload.get("name");
        String newPassword = payload.get("newPassword");

        boolean result = userService.changePassword(account, name, newPassword);
        return result ? R.ok() : R.error();
    }

    @PostMapping("/updatePermission")
    public R updatePermission(@RequestBody Map<String, Object> params) {
        Integer userId = (Integer) params.get("id");
        String permission = (String) params.get("permission");
        boolean isSuccess = userService.updatePermission(userId, permission);
        return isSuccess ? R.ok() : R.error();
    }

    @PostMapping("/login")
    public R loginUser(@RequestBody User user) {
        return userService.loginUser(user.getAccount(), user.getPassword());
    }

    @GetMapping("/getUserById/{id}")
    public R getUserById(@PathVariable Integer id) {
        return R.ok(userService.getUserById(id));
    }

    @GetMapping("/users")
    public R findAllUsers() {
        List<User> result = userService.findAllUsers();
        return R.ok(result);
    }
}
